<template>
  <button class="back-btn" @click="goBack">← 返回</button>
  <div class="chat-container">
    <!-- 空状态提示 -->
    <div v-if="characters.length === 0" class="empty-tip">
      <p class="empty-text">系统暂未设置相关虚拟人物</p>
    </div>
    <!-- 角色列表部分 -->
    <div class="character-list">
      <div class="horizontal-container">
        <div
          v-for="(character, index) in characters"
          :key="index"
          class="character-item"
        >
          <div class="avatar-wrapper">
            <img
              :src="character.avatarUrl"
              class="avatar"
              @click="switchCharacter(character.characterId)"
              :class="{ active: currentCharacterId === character.characterId }"
            />
            <button @click.stop="toggleDropdown(index)" class="dropdown-btn">
              ▼ 详情
            </button>
            <!-- 显示角色的详细信息 -->
            <div v-show="activeIndex === index" class="dropdown-content">
              <h4>{{ character.name }}</h4>
              <p class="detail-item">{{ character.description }}</p>
              <p class="detail-item">
                <strong>性格：</strong>{{ character.personality }}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增对话部分 -->
    <div class="chat-section" v-if="currentCharacterId">
      <div class="chat-messages">
        <div
          v-for="(msg, idx) in currentChat.messages"
          :key="idx"
          class="message"
          :class="msg.type"
        >
          <div class="bubble">{{ msg.content }}</div>
        </div>
      </div>
      <!-- 如果AI正在思考中，显示加载提示 -->
      <div v-if="isThinking" class="thinking-message">
        <div class="bubble">AI正在思考中...</div>
      </div>

      <div class="input-area">
        <input
          v-model="newMessage"
          @keyup.enter="sendMessage"
          placeholder="输入消息..."
        />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getCharacterByBook, createSession, getMessages } from '@/apis/aiChat'
import {
  connectSocket,
  sendSocketMessage,
  closeSocket,
} from '@/utils/websocket' // 引入你的websocket工具
import { useAccountStore } from '@/stores/useAccountStore'

const accountStore = useAccountStore()
const userId = accountStore.uid
const currentCharacterId = ref(null)
const activeIndex = ref(null) // 控制角色详情显示
const newMessage = ref('')
const route = useRoute()
const router = useRouter()
const bookId = route.params.bookId
const currentSessionId = ref(null)
const isThinking = ref(false) // 用于标识AI是否正在思考

const characters = ref([]) // 角色列表
const chatRecords = reactive({})

const currentChat = computed(() => {
  if (!chatRecords[currentCharacterId.value]) {
    chatRecords[currentCharacterId.value] = {
      character: characters.value.find(
        (c) => c.characterId === currentCharacterId.value
      ),
      messages: [],
    }
  }
  return chatRecords[currentCharacterId.value]
})

// 切换角色时，连接新的 WebSocket
const switchCharacter = async (characterId) => {
  currentCharacterId.value = characterId
  activeIndex.value = null

  const character = characters.value.find((c) => c.characterId === characterId)
  if (!character) return

  const sessionData = {
    userId: accountStore.uid,
    characterId: character.characterId,
    characterName: character.name,
    description: character.description,
    personality: character.personality,
    bookName: character.bookName || '',
    greeting: character.greeting || '',
  }

  try {
    const res = await createSession(sessionData)
    console.log('会话创建/获取成功:', res.data)
    currentSessionId.value = res.data

    // 💥 获取历史消息
    const messageRes = await getMessages(currentSessionId.value)
    console.log('历史消息获取成功:', messageRes.data)

    // 把历史消息塞到当前chat里
    chatRecords[characterId] = {
      character,
      messages: messageRes.data.map((msg) => ({
        type: msg.sender === 1 ? 'user' : 'system', // 1是user 2是AI
        content: msg.messageContent,
      })),
    }
  } catch (error) {
    console.error('创建会话或加载历史消息失败:', error)
  }

  // ✅ 不再需要startChatGreeting
  // 开始WebSocket连接
  closeSocket()
  createWebSocketConnection(characterId)
}

// 建立 WebSocket连接
const createWebSocketConnection = (characterId) => {
  const accountUserId = accountStore.uid // 从 store 里拿到用户userId
  const wsUrl = `ws://localhost:8080/ws/aiCharacter-socket?userId=${accountUserId}&characterId=${characterId}`

  connectSocket(wsUrl, (msg) => {
    console.log('收到服务器消息:', msg)

    // 设置 AI 思考结束
    isThinking.value = false

    // 更新聊天记录
    currentChat.value.messages.push({
      type: 'system', // 系统消息，表示 AI 回复的消息
      content: msg.content, // AI 回复的内容
      time: new Date(),
    })
  })
}

// 发送消息，改为通过sendSocketMessage
const sendMessage = () => {
  if (newMessage.value.trim()) {
    // 发送消息前，设置isThinking为true，表示AI正在思考
    isThinking.value = true

    // 添加用户消息到聊天记录
    currentChat.value.messages.push({
      type: 'user', // 消息类型，表示用户发送的消息
      content: newMessage.value.trim(), // 用户输入的消息内容
      time: new Date(), // 发送时间
    })

    // 构建消息数据，发送给后端
    const messageData = {
      userId: accountStore.uid, // 用户ID
      characterId: currentCharacterId.value, // 当前角色ID
      sessionId: currentSessionId.value, // 当前会话ID
      messageContent: newMessage.value.trim(), // 用户输入的消息内容
    }

    // 发送数据到后端
    sendSocketMessage(messageData)

    newMessage.value = '' // 清空输入框

    setTimeout(() => {
      const container = document.querySelector('.chat-messages')
      if (container) container.scrollTop = container.scrollHeight // 滚动到底部
    }, 50)
  }
}

const loadCharacters = async () => {
  try {
    const res = await getCharacterByBook(bookId)
    characters.value = res.data || []
    if (characters.value.length > 0) {
      // 默认加载第一个角色
      await switchCharacter(characters.value[0].characterId)
    }
  } catch (error) {
    console.error('加载角色失败:', error)
  }
}

onMounted(() => {
  loadCharacters()
})

const goBack = () => {
  closeSocket() // 返回页面时顺便关闭socket连接
  router.go(-1)
}

// 切换角色详情展示
const toggleDropdown = (index) => {
  activeIndex.value = activeIndex.value === index ? null : index
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.character-list {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.horizontal-container {
  display: flex;
  gap: 30px;
}

.character-item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 120px;
}

.avatar-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.2s;
  border: 2px solid #eee;
}

.avatar:hover {
  transform: scale(1.1);
  border-color: #409eff;
}

.dropdown-btn {
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 4px 8px;
  cursor: pointer;
  color: #606266;
  font-size: 12px;
  transition: all 0.2s;
}

.dropdown-btn:hover {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.dropdown-content {
  position: absolute;
  top: 110%;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 15px;
  min-width: 240px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.dropdown-content h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 16px;
}

.detail-item {
  margin: 8px 0;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

.back-btn {
  background: none;
  border: none;
  color: #007bff;
  font-size: 16px;
  cursor: pointer;
}

.chat-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 15px;
  max-height: 60vh; /* 可以根据需要调整最大高度 */
}

.message {
  margin: 10px 0;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.bubble {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 15px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message.user .bubble {
  background: #409eff;
  color: white;
}

.input-area {
  display: flex;
  gap: 10px;
}

.input-area input {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
}

.input-area button {
  padding: 12px 24px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: background 0.3s;
}

.input-area button:hover {
  background: #66b1ff;
}

.avatar.active {
  border-color: #409eff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
}

.thinking-message .bubble {
  color: #f5a623;
  font-style: italic;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  min-height: 200px;
}

.empty-icon {
  width: 80px;
  height: 80px;
  opacity: 0.6;
  margin-bottom: 16px;
}

.empty-text {
  color: #909399;
  font-size: 14px;
  text-align: center;
  line-height: 1.6;
}
</style>
